package cn.bjit.util;

import cn.bjit.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
@Slf4j
public class JWTUtil {
    private static final String SUBJECT="yx"; //主题
    private static final String SECRET="yx123456"; //秘钥
    private static final String TOKEN_PREFIX="dcloud-link"; //令牌前缀
    //7天过期
    private static final long EXPIRED=1000*60*60*24*7;

    /**
     * 生成token
     * @return
     */
    public static String geneJsonToken(LoginUser loginUser){
        if(loginUser==null){
            throw new NullPointerException("用户对象为空");
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                //配置payload
                .claim("head_img", loginUser.getHeadImg())
                .claim("account_no", loginUser.getAccountNo())
                .claim("username", loginUser.getUsername())
                .claim("mail", loginUser.getMail())
                .claim("phone", loginUser.getPhone())
                .claim("auth", loginUser.getAuth())
                .claim("ip","111")
                .setIssuedAt(new Date())
                .setExpiration(new Date(CommonUtil.getCurrentTimestamp() + EXPIRED))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token=TOKEN_PREFIX+token;
        return token;
    }
    /**
     * 校验token的方法
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return claims;
        } catch (Exception e) {
            log.info("jwt token解密失败");
            return null;
        }
    }
}
